package com.summer.order.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.summer.core.annotations.ScopeType;
import com.summer.core.controller.EntityHome;
import com.summer.core.service.BaseService;
import com.summer.core.util.ChineseToLetter;
import com.summer.core.util.FacesUtil;
import com.summer.core.util.ImageUploadUtil;
import com.summer.order.model.Food;

@Component
@Scope(ScopeType.VIEW)
public class FoodHome extends EntityHome<Food> {

	@Resource
	BaseService<Food> baseService;
	
	@Transactional(readOnly = false , rollbackFor = Exception.class)
	public String save() {
		
		Food food = getInstance();
		if(food.getId() == null || food.getId().equals("")) {
			food.setId(ChineseToLetter.getPingYin(food.getName()));
			
		}
		baseService.merge(food);
		
		return FacesUtil.redirect("/admin/order/foodList");
	}
	
	public void uploadFoodPicture(FileUploadEvent event) {
		UploadedFile uploadFile = event.getFile();
		InputStream is = null;
		try {
			is = uploadFile.getInputstream();
			String res = ImageUploadUtil.upload(is, uploadFile.getFileName());
			this.getInstance().setPicture(res);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
	}
	
}
